package com.iqiyi.pps.epg.web.webapp.filter;

import com.iqiyi.pps.epg.core.infrastructure.context.UserContext;
import com.iqiyi.pps.epg.core.model.auth.SysUser;
import com.iqiyi.pps.epg.core.utils.SpringSecurityUtils;
import com.iqiyi.pps.epg.web.utils.RequestUtils;
import org.apache.commons.lang.RandomStringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: lishunlong
 * Date: 12-6-25
 * Time: 下午5:25
 * To change this template use File | Settings | File Templates.
 */
public class UserContextFilter implements Filter {
    public static final int TRACE_ID_LENGTH = 10;

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        try {
            UserContext context = UserContext.getContext();

            SysUser user = (SysUser) SpringSecurityUtils.getCurrentUser();
            if(user != null) {
                context.setId(String.valueOf(user.getId()));
                context.setName(user.getLoginName());
            }

            context.setIp(RequestUtils.getRemoteAddr(request));
            context.setTransId(RandomStringUtils.randomAlphanumeric(TRACE_ID_LENGTH));
            chain.doFilter(request, response);
        } finally {
            UserContext.cleanupContext();
        }
    }

    public void destroy() {
    }
}
